package com.ant.storage.service.impl;

import com.ant.storage.dataSource.DynamicDataSource;
import com.ant.storage.dataSource.DynamicDataSourceContextHolder;
import com.ant.storage.mapper.DataMsgMapper;
import com.ant.storage.pojo.DataMsg;
import com.ant.storage.service.IDataMsgService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hzd
 * @since 2024-07-19
 */
@Service
public class DataMsgServiceImpl extends ServiceImpl<DataMsgMapper, DataMsg> implements IDataMsgService {



    private DynamicDataSource dynamicDataSource;

    public DataMsgServiceImpl(DynamicDataSource dynamicDataSource1){
        this.dynamicDataSource = dynamicDataSource1;
    }

    @Override
    public List<DataMsg> get() {
        return this.baseMapper.selectList(null);
    }

    @Override
    public boolean changeDb(Integer cityId) throws Exception ,SQLException{
        //默认切换到主数据源，进行整体资源的查找
        try {
            DynamicDataSourceContextHolder.clearDataSource();
            List<DataMsg> dataSourceList = this.baseMapper.selectList(null);
            for (DataMsg source : dataSourceList) {
                if (source.getCityId().equals(cityId)) {
                    //创建数据源连接&检查，若存在则不需要重新创建
                    boolean dataSourceWithCheck = dynamicDataSource.createDataSourceWithCheck(source);
                    if(dataSourceWithCheck){
                        DynamicDataSourceContextHolder.setDataSourceType(source.getCityId().toString());
                        return true;
                    }
                    //切换到该数据源
                    return false;
                }
            }
            return false;
        }catch (SQLException e) {
            e.printStackTrace();
        }catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean delDb() throws Exception {
        Object key = dynamicDataSource.determineCurrentLookupKey();
        if (key != null) {
            //如果当前数据源就是要删除的数据源，则切换到默认数据源
            DynamicDataSourceContextHolder.clearDataSource();
            return true;
        }
        return false;
    }
}
